package cn.itcast.mobile_weather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    String url = "https://www.jianshu.com/p/b7bd922195f9";

    SwipeRefreshLayout refreshLayout;

    TextView cityTextView;
    TextView tempTextView;
    TextView weatherTextView;
    TextView windDirectionTextView;
    TextView powerTextView;
    TextView humidityTextView;
    TextView reportTimeTextView;
    TextView lastTextView;
    EditText editTextCity;
    Button btnSubmit;

    String city="";
    SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp=this.getPreferences(MODE_PRIVATE);
        city=sp.getString("city","普宁市");

        cityTextView = findViewById(R.id.tv_city);
        tempTextView = findViewById(R.id.tv_temp);
        weatherTextView = findViewById(R.id.tv_weather);
        windDirectionTextView = findViewById(R.id.tv_wind_direction);
        powerTextView = findViewById(R.id.tv_wind_power);
        humidityTextView = findViewById(R.id.tv_wind_humidity);
        reportTimeTextView = findViewById(R.id.tv_wind_report_time);
        lastTextView=findViewById(R.id.tv_last);
        refreshLayout=findViewById(R.id.refresh_layout);
        editTextCity=findViewById(R.id.edit_city);
        btnSubmit=findViewById(R.id.btn_submit);



        requestHttp();
        //启动时先显示刷新球
        refreshLayout.setRefreshing(true);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestHttp();
            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                city= editTextCity.getText().toString();
                //保存用户搜索过的城市
                SharedPreferences.Editor editor=sp.edit();
                editor.putString("city",city);
                editor.commit();
                requestHttp();
            }
        });
    }

    void requestHttp() {

        //？问号之后是参数，参数的形式是xxx=yyy,参数之间分隔使用&符号
        String url = "https://www.mxnzp.com/api/weather/current/"+handerCity(city)+"?app_id=" + Commons.APP_ID + "&app_secret=" + Commons.APP_KEY;

        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //404或其他的是失败
                Log.e("MainActivity", "onFailure请求失败");

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //200成功
                final String result = response.body().string();//请求成功后服务器返回的结果
                Log.e("result", result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    final String dataString = jsonObject.optString("data");
                    Log.e("json:", dataString);

                    Gson gson = new Gson();
                    final WeatherBean weatherBean = gson.fromJson(dataString, WeatherBean.class);//反射
                    updateUI(weatherBean);
                    //refreshLayout.setRefreshing(false)可以在子线程里执行
                    refreshLayout.setRefreshing(false);


                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        });
    }

    void updateUI(final WeatherBean weatherBean) {

        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cityTextView.setText("城市:" + weatherBean.getAddress());

                tempTextView.setText("温度:" + weatherBean.getTemp());
                weatherTextView.setText("天气:" + weatherBean.getWeather());

                windDirectionTextView.setText("风向:" + weatherBean.getWindDirection());
                powerTextView.setText("风力:" + weatherBean.getWindPower());
                humidityTextView.setText("湿度:" + weatherBean.getHumidity());
                reportTimeTextView.setText("时间:" + weatherBean.getReportTime());
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String current = df.format(System.currentTimeMillis());
                lastTextView.setText("数据请求时间"+current);

            }
        });
    }

    //用户如果输入一个字符串，没有以“市”结尾，那么返回值 加上“市”
    String handerCity(String city){
          if(city.endsWith("市")){
              return city;
          }else{
              return city+"市";
          }
    }
}
